//
//  JXLEmoticonKeyBoard.swift
//  MicroBlog
//
//  Created by 贾晓磊 on 16/10/6.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//
//自定义表情键盘视图
/*
 1. 表情视图 -> UICollectionView
 2. 页数指示器 -> UIPageControl
 3. toolBar -> UIStackView
 */

import UIKit

//  重用标记
private let JXLEmoticonCollectionViewCellIdentifier = "JXLEmoticonCollectionViewCellIdentifier"

class JXLEmoticonKeyBoard: UIView {

    //页码指示器
    private var pageControl: UIPageControl = {
        let control = UIPageControl()
        //当前选中页数的颜色
        control.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named:"compose_keyboard_dot_selected")!)
        //默认页数的颜色
        control.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        //单页隐藏
        control.hidesForSinglePage = true
        
        return control
    }()
    
        //表情视图
    fileprivate lazy var emoticonCollectionView: UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        view.backgroundColor = self.backgroundColor
        
        //设置水平滚动方向
        flowLayout.scrollDirection = .horizontal
        //开启分页
        view.isPagingEnabled = true
        //隐藏水平和垂直方向的滚动条
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        //去掉弹簧效果
        view.bounces = false
        
        //注册cell
        view.register(JXLEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: JXLEmoticonCollectionViewCellIdentifier)
        //设置数据源代理
        view.dataSource = self
        //设置代理
        view.delegate = self
        
        return view
    }()
    
    // 底部toolBar
    fileprivate lazy var emoticonKindToolBar: JXLEmoticonToolBar = JXLEmoticonToolBar()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() -> Void {
        //设置背景颜色
        //backgroundColor = UIColor.red
        //把图片颜色设置为背景颜色
        backgroundColor = UIColor(patternImage: UIImage(named:"emoticon_keyboard_background")!)
        
        //设置滚动到IndexPath
        let normalIndexPath = IndexPath(item: 0, section: 1)
        //  主线程异步,等待其它视图初始化完成和绑定数据完成后,然后在执行滚动到指定IndexPath
        DispatchQueue.main.async { 
            //  设置滚动默认的这组表情数据
            self.emoticonCollectionView.scrollToItem(at: normalIndexPath, at: .left, animated: false)
        }
        
        //获取默认page的数据
        self.setPageControlData(indexPath: normalIndexPath)
        
        //添加子控件
        addSubview(emoticonCollectionView)
        addSubview(emoticonKindToolBar)
        addSubview(pageControl)
        //emoticonCollectionView 设置约束
        emoticonCollectionView.snp_makeConstraints { (make) in
            make.leading.top.trailing.equalTo(self)
            make.bottom.equalTo(emoticonKindToolBar.snp_top)
        }
        
        //emoticonKindToolBar 设置约束
        emoticonKindToolBar.snp_makeConstraints { (make) in
            make.bottom.leading.trailing.equalTo(self)
            make.height.equalTo(35)
        }
        //pageControl设置约束
        pageControl.snp_makeConstraints { (make) in
            make.bottom.equalTo(emoticonCollectionView)
            make.centerX.equalTo(emoticonCollectionView)
            make.height.equalTo(10)
        }
        
        //给底部toolBar的闭包赋值
        emoticonKindToolBar.callBack = { [weak self] (type: JXLEmoticonToolBarButtonType) in
            
            let indexPath: IndexPath
            
            switch type {
            case .recent:
                print("最近")
                indexPath = IndexPath(item: 0, section: 0)

            case .normal:
                print("默认")
                indexPath = IndexPath(item: 0, section: 1)

            case .emoji:
                print("emoji")
                indexPath = IndexPath(item: 0, section: 2)

            case .lxh:
                print("浪小花")
                indexPath = IndexPath(item: 0, section: 3)

            }
            //  把collectionView滚动到指定的indexpath上
            //  不需要开启动画, 设置flase
            self?.emoticonCollectionView.scrollToItem(at: indexPath, at: .left, animated: false)

            //  点击按钮，pagecontrol滚动到相应的页码
            self?.setPageControlData(indexPath: indexPath)
        }

    }
    
    //设置表情视图条目的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        //获取布局方式
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //设置cell大小
        flowLayout.itemSize = emoticonCollectionView.size
        //设置被迫换行间距
        flowLayout.minimumLineSpacing = 0
        //设置间距
        flowLayout.minimumInteritemSpacing = 0
        
    }
    
    //设置pageControl数据
    func setPageControlData(indexPath: IndexPath) -> Void {
        pageControl.numberOfPages = JXLEmoticonTools.sharedTools.allEmoticonArray[indexPath.section].count
        pageControl.currentPage = indexPath.item
    }

    
}


extension JXLEmoticonKeyBoard: UICollectionViewDataSource, UICollectionViewDelegate {
   
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return JXLEmoticonTools.sharedTools.allEmoticonArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return JXLEmoticonTools.sharedTools.allEmoticonArray[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JXLEmoticonCollectionViewCellIdentifier, for: indexPath) as! JXLEmoticonCollectionViewCell
        
        cell.indexPath = indexPath
        
        //给cell的数据源模型赋值
        cell.emoticonsArray = JXLEmoticonTools.sharedTools.allEmoticonArray[indexPath.section][indexPath.item]
        
        return cell
    }
    
    //MARK: 代理方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //监听滚动，获取表情的中心点(方法一)
        let centerX = scrollView.contentOffset.x + emoticonCollectionView.width / 2
        let centerY = scrollView.contentOffset.y + emoticonCollectionView.height / 2
        //拿到中心点
        let center = CGPoint(x: centerX, y: centerY)
        
        //拿到中心点，方法二
        //  通过坐标的转换
        //  把emoticonCollectionView在HMEmoticonKeyBoard上中心点转换成在表情视图(emoticonCollectionView)的中心点上
//        let center1 = self.convert(emoticonCollectionView.center, to: emoticonCollectionView)
        
        
        //通过中心点，获取对应cell的indexPath
        if let indexPath = emoticonCollectionView.indexPathForItem(at: center) {
            //获取对应的section
            let section = indexPath.section
            
            //通过section选中相应的按钮
        emoticonKindToolBar.selectedButton(section: section)
            self.setPageControlData(indexPath: indexPath)
        }
    }
}
